unit XMLSerializer;

interface

uses
 Classes,
 JvgXMLSerializer;

type
 TXMLSerializer = class
 private
  XS: TJvgXMLSerializer;
  FS: TFileStream;
  procedure GetXMLHeader(Sender: TObject; var Value: String);
 public
  constructor Create;
  destructor Destroy; override;
  //
  function Serialize(const anObject: TObject; const Filename: String): Integer;
  function DeSerialize(const anObject: TObject; const Filename: String): Integer;
 end;

implementation

uses
 SysUtils;

 { TXMLSerializer }

constructor TXMLSerializer.Create;
begin
 inherited;
 XS := TJvgXMLSerializer.Create(nil);
 XS.OnGetXMLHeader:=GetXMLHeader;
 FS := nil;
end;

destructor TXMLSerializer.Destroy;
begin
 if Assigned(FS) then
   FreeAndNil(FS);
 FreeAndNil(XS);
 inherited;
end;

procedure TXMLSerializer.GetXMLHeader(Sender: TObject; var Value: String);
begin
 Value := '<?xml version="1.0" encoding="windows-1251"?>';
end;

function TXMLSerializer.Serialize(const anObject: TObject; const Filename: String): Integer;
begin
 Result:=0;
 if Assigned(anObject) and (Filename<>'') then
  begin
   FS := TFileStream.Create(Filename, fmCreate);
   try
    XS.Serialize(anObject, FS);
   except
    on E: Exception do
     begin
      Result:=GetLastError;
     end;
   end;
   FreeAndNil(FS);
  end
 else
   Result:=-1;
end;

function TXMLSerializer.DeSerialize(const anObject: TObject; const Filename: String): Integer;
begin
 Result:=0;
 if Assigned(anObject) and (FileExists(Filename)) then
  begin
   FS := TFileStream.Create(Filename, fmOpenRead);
   try
    XS.DeSerialize(anObject, FS);
   except
    on E: Exception do
     begin
      Result:=GetLastError;
     end;
   end;
   FreeAndNil(FS);
  end
 else
   Result:=-1;
end;

end.
